package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.SearchArticleVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDto dto, boolean isFirst) {
        // 1. 判断，当前调用这个方法的控制器是不是首页，如果是就展示redis里面的数据
        if(isFirst) {
            String cache = redisTemplate.opsForValue().get(ArticleConstants.LOADTYPE_LOAD_MORE + dto.getTag());
            List<HotArticleVo> hotArticleVos = JSON.parseArray(cache, HotArticleVo.class);
            return ResponseResult.okResult(hotArticleVos);
        }

        // 2. 如果不是就走原来的查询数据库流程
        return load(loadtype, dto);
    }

    @Override
    public ResponseResult load(Short loadType, ArticleHomeDto dto) {
        List<ApArticle> articles = apArticleMapper.loadArticleList(dto, loadType);
        return ResponseResult.okResult(articles);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        // 1. dto判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2. 将dto中数据，直接赋值到ApArticle对象中
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        // 3. 判断dto里面的id是否存在，存在代表修改，不存在代表新增
        Long id = dto.getId();

        // 3. 不存在 -> 新增
        if (id == null) {
            // 3.1 将前面组装好的ApArticle对象，插入article表
            int insertArticleResult = apArticleMapper.insert(apArticle);
            if (insertArticleResult != 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            // 3.2 插入article_config表
            ApArticleConfig config = new ApArticleConfig();
            // 填充字段(is_down,is_delete,is_forward,is_comment,article_id)
            config.setIsForward(true);
            config.setIsDown(false);
            config.setIsDelete(false);
            config.setIsComment(true);
            config.setArticleId(apArticle.getId());

            int insertConfigResult = apArticleConfigMapper.insert(config);
            if (insertConfigResult != 1) {
                throw new RuntimeException("配置插入失败");
            }

            // 3.3 插入article_content表
            ApArticleContent content = new ApArticleContent();
            content.setContent(dto.getContent());
            content.setArticleId(apArticle.getId());
            // 填充字段(content,article_id)
            int insertContentResult = apArticleContentMapper.insert(content);
            if (insertContentResult != 1) {
                throw new RuntimeException("内容插入失败");
            }

            // 3.4 返回文章id
            return ResponseResult.okResult(apArticle.getId());
        }

        // 4. id存在 -> 修改
        else {
            // 4.1  将前面组装好的ApArticle对象，修改article表
            int updateArticleResult = apArticleMapper.updateById(apArticle);
            if (updateArticleResult != 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }

            // 4.2 修改article_content表
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, apArticle.getId());

            ApArticleContent content = new ApArticleContent();
            content.setContent(dto.getContent());

            int updateContentResult = apArticleContentMapper.update(content, wrapper);
            if (updateContentResult != 1) {
                throw new RuntimeException("内容修改失败");
            }
        }

        // 5. 将articleId返回回去
        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public void createArticleESIndex(ApArticle apArticle, String content) {
        if (apArticle == null) {
            return;
        }

        // 方法接收到两个参数 apArticle , content
        // 新建一个VO 这个vo包含 apArticle + content 所有字段
        // 新建一个Map
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);

        // 参数一：发给哪个队列
        // 参数二：发什么消息
        rabbitTemplate.convertAndSend("es.queue", JSON.toJSONString(vo));
    }
}